package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.app.AppConstants;
import com.heima.common.exception.config.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    ApUserMapper apUserMapper;
    /**
     * app用户登录
     * 手机号登录和游客登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //1.参数校验
        if (loginDto==null||loginDto.getEquipmentId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.用手机号登录
        if (StringUtils.isNotBlank(loginDto.getPhone())&&StringUtils.isNotBlank(loginDto.getPassword())){
            //查询当前手机号用户是否存在
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, loginDto.getPhone())
                    .eq(ApUser::getStatus, AppConstants.AP_USER_ISSTATUS));//0状态正常
            if (apUser==null){
                CustException.cust("当前手机号不存在或者密码错误");
            }
            String salt = apUser.getSalt();//盐
            String dbpassword = apUser.getPassword();//数据库里加密后的密码
            String password = DigestUtils.md5DigestAsHex((loginDto.getPassword() + salt).getBytes());
            if (!password.equals(dbpassword)){
                CustException.cust("当前手机号不存在或者密码错误");
            }
            //生成jwt令牌，将用户信息返回
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            Map<String, Object> map=new HashMap<>();
            apUser.setPassword(null);
            apUser.setSalt(null);
            map.put("token",token);
            map.put("user",apUser);
            return ResponseResult.okResult(map);

        }else {
            //游客登录 id=0
            Map<String, Object>map=new HashMap<>();
            String token = AppJwtUtil.getToken(0L);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
